package com.web.farme.pojo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2021/4/18 上午8:26
 * @Created by sakura
 * 全局异常处理器
 */
@RestControllerAdvice(annotations = {RestController.class})
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Results<?> bizExceptionHandler(BizException e) {
        logger.error(e.errorMsg, e.errorCode);
        return Results.buildFail(e.errorMsg, e.errorCode);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Results<?> exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知异常！原因是:", e);
        return Results.buildFail("接口异常");
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Results<?> bindExceptionHandler(MethodArgumentNotValidException e) {
        StringBuilder stringBuffer = new StringBuilder();
        logger.error("发生参数校验异常");
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            stringBuffer.append(allError.getDefaultMessage()).append(" ");
        }
        return Results.buildFail(stringBuffer.toString());
    }

    @ExceptionHandler(value = BindException.class)
    public Results<?> bindExceptionHandler(HttpServletRequest request, BindException e) {
        StringBuilder stringBuffer = new StringBuilder();
        logger.error("发生参数校验异常");
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            stringBuffer.append(allError.getDefaultMessage()).append(" ");
        }
        return Results.buildFail(stringBuffer.toString());
    }


    /**
     * 参数类型转换错误
     *
     * @param exception 错误
     * @return 错误信息
     */
    @ExceptionHandler(HttpMessageConversionException.class)
    public Results<?> parameterTypeException(HttpMessageConversionException exception) {
        logger.error(exception.getMessage());
        return Results.buildFail("前端类型异常");
    }


}
